package bubbleSort;

import shared.Buffer;


public class BubbleSortManagerSequential<T extends Comparable<? super T>>
{	
	public Buffer<T> sort(final Buffer<T> buffer) {
		final Buffer<T> clone = buffer.clone();
		return this.loopThroughOnce(clone);
	}

	private Buffer<T> loopThroughOnce(final Buffer<T> buffer) {
		boolean changed = false;
		final Buffer<T> newBuffer = new Buffer<T>();
		while(!buffer.isEmpty()){
			final T first = buffer.get();
			changed = extracted(buffer, changed, newBuffer, first);
		}
		return changed ? this.loopThroughOnce(newBuffer) : newBuffer;
	}

	private boolean extracted(final Buffer<T> buffer, boolean changed,
			final Buffer<T> newBuffer, final T first) {
		if(!buffer.isEmpty()){
			final T second = buffer.get();
			if(first.compareTo(second) > 0){
				newBuffer.put(second);
				changed = true;
				extracted(buffer, changed, newBuffer, first);
			} else {
				newBuffer.put(first);
				changed = extracted(buffer, changed, newBuffer, second);
			}
		} else{
			newBuffer.put(first);
		}
		return changed;
	}
}
